#include <math.h> 
#include <allegro.h> 
#include <apeg.h>


int PlayVideo(const char *filename, int loop) 



{

    float ratio,w,h,x,y;

    APEG_STREAM *stream;

    set_volume_per_voice(0); 

    apeg_set_display_depth(32); 

    apeg_ignore_video(0); 

    apeg_ignore_audio(0); 

    stream = apeg_open_stream(filename);

    if(!stream)

    {

        allegro_message("APEG Error: %s\n", apeg_error);

        return APEG_ERROR; 

    }

    if(!(stream->flags & APEG_HAS_VIDEO)) 

    {

        allegro_message("No video\n");

        apeg_close_stream(stream);

        return APEG_ERROR; 
    }

    apeg_reset_colors(stream);

    rest(100); 
    //On calcule la position exacte de la video dans l'ecran (aspect ratio)

    ratio=fmax((float)stream->w/(float)SCREEN_W , (float)stream->h/(float)SCREEN_H);

    w=(float)stream->w/ratio;

    h=(float)stream->h/ratio;

    x=(float)SCREEN_W/2.0f - (float)w/2.0f;

    y=(float)SCREEN_H/2.0f - (float)h/2.0f;


    stream->timer = -1;


    while(stream->timer == -1);

    while(apeg_advance_stream(stream, loop) == APEG_OK)

    {

        if(key[KEY_ESC])

            break;

        if(stream->frame_updated > 0)

        {

            stretch_blit(stream->bitmap,screen, 0, 0, stream->bitmap->w, stream->bitmap->h, x, y, w, h);

        }

        else

        {

            if(stream->frame_updated < 0 && !stream->audio.flushed)

                rest(1);

        }

    }

    apeg_close_stream(stream);

    return APEG_OK;

}



int main()

{

    if(allegro_init() != 0)

    {

        return -1;

    }

    install_keyboard();

    install_timer();

    install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL);

    set_color_depth(32);

    if(set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1280, 1024, 0, 0) != 0)

    {

        return -1;

    }

    clear_to_color(screen, makecol(0, 0, 0));

    //apeg_play_mpg("example.ogg", screen, FALSE, NULL); //pour jouer la video

    PlayVideo("introsample.ogg",1);

    return 0;

}

END_OF_MAIN()
